import {
  login,
  logout,
  getUserInfo,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash,
  getUnreadCount
} from '@/api/user'
import {
  setToken,
  getToken,
  removeToken
} from '@/libs/util'
import store from '@/libs/store/cookie'
const LOGIN_KEY = 'login_status'
export default {
  state: {
    userName: '',
    userId: '',
    avatarImgPath: '',
    token: store.get(LOGIN_KEY) || null,
    access: '',
    userInfo: null,
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {}
  },
  mutations: {
    setAvatar (state, avatarPath) {
      state.avatarImgPath = avatarPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
    },
    LOGOUT (state) {
      state.token = undefined
      removeToken()
    },
    setAccess (state, access) {
      state.access = access
    },
    UPDATE_USERINFO (state, userInfo) {
      state.userInfo = userInfo
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    LOGIN (state, datas) {
      state.token = datas.token
      state.expires_time = datas.expires_time
      store.set(LOGIN_KEY, datas.token, datas.expires_time)
      store.set('expires', datas.expires_time)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, {
      msg_id,
      content
    }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg (state, {
      from,
      to,
      msg_id
    }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin ({
      commit
    }, {
      userName,
      password,
      user_type
    }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        try {
          login({
            userName,
            password,
            user_type
          }).then(res => {
            const data = res.data
            if (data) {
              let expires_time = data.expires_time.substring(0, 19)
              expires_time = expires_time.replace(/-/g, '/')
              expires_time = new Date(expires_time).getTime()
              console.log(expires_time)
              const datas = {
                token: data.token,
                expires_time: expires_time
              }
              commit('setUserId', data.admin_id)
              commit('LOGIN', datas)
              commit('setToken', data.token)
              store.set('admin_id', data.admin_id)

              resolve(res)
            } else {
              resolve(res)
            }
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    // 退出登录
    handleLogOut ({
      state,
      commit
    }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('LOGOUT', '')
          commit('setAccess', [])
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取用户相关信息
    getUserInfo ({
      state,
      commit
    }) {
      return new Promise((resolve, reject) => {
        const adminId = state.userId ? state.userId : store.get('admin_id')
        console.log('id=' + adminId)
        try {
          getUserInfo(adminId).then(res => {
            const data = res.data
            commit('setAvatar', data.avatar)
            commit('setUserName', data.nickname)
            commit('setAccess', data.access)
            commit('UPDATE_USERINFO', data)
            commit('setHasGetInfo', true)
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
    // // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    // getUnreadMessageCount ({
    //   state,
    //   commit
    // }) {
    //   getUnreadCount().then(res => {
    //     const {
    //       data
    //     } = res
    //     commit('setMessageCount', data)
    //   })
    // },
    // // 获取消息列表，其中包含未读、已读、回收站三个列表
    // getMessageList ({
    //   state,
    //   commit
    // }) {
    //   return new Promise((resolve, reject) => {
    //     getMessage().then(res => {
    //       const {
    //         unread,
    //         readed,
    //         trash
    //       } = res.data
    //       commit('setMessageUnreadList', unread.sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
    //       commit('setMessageReadedList', readed.map(_ => {
    //         _.loading = false
    //         return _
    //       }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
    //       commit('setMessageTrashList', trash.map(_ => {
    //         _.loading = false
    //         return _
    //       }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // // 根据当前点击的消息的id获取内容
    // getContentByMsgId ({
    //   state,
    //   commit
    // }, {
    //   msg_id
    // }) {
    //   return new Promise((resolve, reject) => {
    //     let contentItem = state.messageContentStore[msg_id]
    //     if (contentItem) {
    //       resolve(contentItem)
    //     } else {
    //       getContentByMsgId(msg_id).then(res => {
    //         const content = res.data
    //         commit('updateMessageContentStore', {
    //           msg_id,
    //           content
    //         })
    //         resolve(content)
    //       })
    //     }
    //   })
    // },
    // // 把一个未读消息标记为已读
    // hasRead ({
    //   state,
    //   commit
    // }, {
    //   msg_id
    // }) {
    //   return new Promise((resolve, reject) => {
    //     hasRead(msg_id).then(() => {
    //       commit('moveMsg', {
    // //         from: 'messageUnreadList',
    //         to: 'messageReadedList',
    //         msg_id
    //       })
    //       commit('setMessageCount', state.unreadCount - 1)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // // 删除一个已读消息到回收站
    // removeReaded ({
    //   commit
    // }, {
    //   msg_id
    // }) {
    //   return new Promise((resolve, reject) => {
    //     removeReaded(msg_id).then(() => {
    //       commit('moveMsg', {
    //         from: 'messageReadedList',
    //         to: 'messageTrashList',
    //         msg_id
    //       })
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // // 还原一个已删除消息到已读消息
    // restoreTrash ({
    //   commit
    // }, {
    //   msg_id
    // }) {
    //   return new Promise((resolve, reject) => {
    //     restoreTrash(msg_id).then(() => {
    //       commit('moveMsg', {
    //         from: 'messageTrashList',
    //         to: 'messageReadedList',
    //         msg_id
    //       })
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // }
  }
}
